﻿using System.Configuration;
using System.IO.Ports;

namespace SerialPortTrans2
{
    /// <summary>
    /// 表示串口配置节。
    /// </summary>
    public sealed class SerialPortConfigSection : ConfigurationSection
    {
        /// <summary>
        /// 端口名称。
        /// </summary>
        [ConfigurationProperty("portName", DefaultValue = "COM1", IsRequired = true)]
        public string PortName
        {
            get { return (string)this["portName"]; }
            set { this["portName"] = value; }
        }

        /// <summary>
        /// 波特率。
        /// </summary>
        [ConfigurationProperty("baudRate", DefaultValue = 9600, IsRequired = true)]
        public int BaudRate
        {
            get { return (int)this["baudRate"]; }
            set { this["baudRate"] = value; }
        }

        /// <summary>
        /// 奇偶校验位。
        /// </summary>
        [ConfigurationProperty("parity", DefaultValue = Parity.None, IsRequired = true, IsKey = false)]
        public Parity Parity
        {
            get { return (Parity)this["parity"]; }
            set { this["parity"] = value; }
        }

        /// <summary>
        /// 数据位长度。
        /// </summary>
        [ConfigurationProperty("dataBits", DefaultValue = 8, IsRequired = true)]
        public int DataBits
        {
            get { return (int)this["dataBits"]; }
            set { this["dataBits"] = value; }
        }

        /// <summary>
        /// 标准停止位数。
        /// </summary>
        [ConfigurationProperty("stopBits", DefaultValue = StopBits.One, IsRequired = true, IsKey = false)]
        public StopBits StopBits
        {
            get { return (StopBits)this["stopBits"]; }
            set { this["stopBits"] = value; }
        }

        /// <summary>
        /// 创建串口对象实例。
        /// </summary>
        /// <returns></returns>
        internal SerialPort Create()
        {
            return new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
        }
    }
}